package org.posta.mail.server;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.posta.data.UserStore;
import org.posta.data.user.User;
import org.posta.mail.store.MailMessage;
import org.posta.mail.store.MailStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.subethamail.smtp.MessageListener;
import org.subethamail.smtp.TooMuchDataException;

import com.google.inject.Inject;

public class MessageHandler implements MessageListener
{
    
    private static Logger log = LoggerFactory.getLogger(MessageHandler.class);
    
    @Inject
    private UserStore     userStore;
    
    @Inject
    private MailStore     mailStore;
    
    public boolean accept(String from, String recipient)
    {
        // TODO: Check when to accept
        try
        {
            InternetAddress address = new InternetAddress(recipient);
            log.debug("Name: {}", address.getAddress());
        } catch (AddressException e)
        {
            log.debug("Invalid address: {}", recipient);
            return false;
        }
        
        return true;
    }
    
    public void deliver(String from, String recipient, InputStream data)
            throws TooMuchDataException, IOException
    {
        log.info("New mail from '{}' to '{}'", from, recipient);
        // Message message = new Message(data);
        // message.writeTo(System.out);
        
        Session session = Session.getDefaultInstance(new Properties());
        try
        {
            MimeMessage message = new MimeMessage(session, data);
            Address address = message.getSender();
            
            User user = userStore.getByName(recipient);
            mailStore.add(new MailMessage(user, message));
            
        } catch (MessagingException e)
        {
            log.error("Error decoding mime message", e);
            throw new IOException(e.getMessage());
        }
    }
    
}
